#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
头条自动发文系统 - 快速安装脚本
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def print_header():
    """打印安装头部信息"""
    print("🎯 头条自动发文系统 - 快速安装")
    print("=" * 40)
    print()

def check_python():
    """检查Python版本"""
    print("🔍 检查Python环境...")
    
    if sys.version_info < (3, 8):
        print(f"❌ Python版本过低: {sys.version}")
        print("   需要Python 3.8或更高版本")
        return False
    
    print(f"✅ Python版本: {sys.version.split()[0]}")
    return True

def install_dependencies():
    """安装依赖包"""
    print("\n📦 安装依赖包...")
    
    try:
        # 升级pip
        print("   📈 升级pip...")
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", "--upgrade", "pip"
        ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        
        # 安装依赖
        print("   📥 安装项目依赖...")
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", "-r", "requirements.txt"
        ])
        
        print("✅ 依赖包安装完成")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖包安装失败: {e}")
        return False

def setup_config():
    """设置配置文件"""
    print("\n⚙️  配置系统...")
    
    # 创建.env文件
    env_file = Path(".env")
    env_example = Path("env_example.txt")
    
    if not env_file.exists() and env_example.exists():
        try:
            shutil.copy(env_example, env_file)
            print("✅ 创建配置文件: .env")
        except Exception as e:
            print(f"❌ 创建配置文件失败: {e}")
            return False
    
    # 创建必要目录
    directories = ["uploads", "cookies", "browser_data", "static", "templates"]
    for directory in directories:
        Path(directory).mkdir(exist_ok=True)
    
    print("✅ 目录结构创建完成")
    return True

def check_installation():
    """检查安装结果"""
    print("\n🔍 验证安装...")
    
    # 检查关键模块
    modules = ["fastapi", "uvicorn", "requests", "DrissionPage"]
    
    for module in modules:
        try:
            __import__(module)
            print(f"   ✓ {module}")
        except ImportError:
            print(f"   ✗ {module}")
            return False
    
    print("✅ 安装验证通过")
    return True

def show_usage():
    """显示使用说明"""
    print("\n📖 使用说明")
    print("-" * 20)
    print("1. 编辑 .env 文件，填入您的DeepSeek API密钥:")
    print("   DEEPSEEK_API_KEY=your_api_key_here")
    print()
    print("2. 启动系统:")
    print("   python run.py")
    print("   或双击: 启动系统.bat")
    print()
    print("3. 访问系统:")
    print("   http://localhost:8000")
    print()
    print("🔗 获取DeepSeek API密钥:")
    print("   https://platform.deepseek.com")
    print()

def main():
    """主安装函数"""
    print_header()
    
    # 检查Python环境
    if not check_python():
        input("按Enter键退出...")
        return False
    
    # 安装依赖
    if not install_dependencies():
        input("按Enter键退出...")
        return False
    
    # 设置配置
    if not setup_config():
        input("按Enter键退出...")
        return False
    
    # 验证安装
    if not check_installation():
        input("按Enter键退出...")
        return False
    
    print("\n🎉 安装完成！")
    print("=" * 40)
    
    # 显示使用说明
    show_usage()
    
    # 询问是否立即启动
    try:
        choice = input("是否立即启动系统？(y/n): ").lower().strip()
        if choice in ['y', 'yes', '是', '']:
            print("\n🚀 启动系统...")
            subprocess.call([sys.executable, "run.py"])
    except KeyboardInterrupt:
        print("\n👋 安装完成，您可以稍后手动启动系统")
    
    return True

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n👋 安装已取消")
    except Exception as e:
        print(f"\n❌ 安装过程中发生错误: {e}")
        input("按Enter键退出...")
